package com.jerry.hm.algorithm.recursion;

/**
 * 递归的二分查找
 *
 * @author Jerry
 * @since 2024/9/30 19:15
 */
public class BinarySearch {

    public static int search(int[] arr, int target) {
        return fun(arr, target, 0, arr.length - 1);
    }

    /**
     * 二分查找
     *
     * @param arr
     * @param target
     * @param left   左边界
     * @param right  右边界
     * @return
     */
    private static int fun(int[] arr, int target, int left, int right) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) >>> 1;
        if (target < arr[mid]) {
            return fun(arr, target, left, mid - 1);
        } else if (target > arr[mid]) {
            return fun(arr, target, mid + 1, right);
        } else {
            return mid;
        }
    }
}
